package zhenai

import (
    "fmt"
    "github.com/gpmgo/gopm/modules/log"
    "reflect"
    "regexp"
    "spider/simple/model"
    "spider/simple/parser"
)

// 用户解析器
// 解析結果 用户信息
type UserParser struct {
}

var regexs = map[string]*regexp.Regexp{
    "Name":       regexp.MustCompile(`<a class="name fs24">(.+)</a>`),
    
    "Age":        regexp.MustCompile(`<td><span class="label">年龄：</span>(?:<span field="">)*([^<]+)(?:</span>)*</td>`),
    
    "Sex":        regexp.MustCompile(`<td><span class="label">性别：</span><span field="">(?:<span field="">)*([^<]+)(?:</span>)*</span></td>`),
    
    "Height":     regexp.MustCompile(`<td><span class="label">身高：</span>(?:<span field="">)*([^<]+)(?:</span>)*</td>`),
    
    "Marriage":   regexp.MustCompile(`<td><span class="label">婚况：</span>(?:<span field="">)*([^<]+)(?:</span>)*</td>`),
    
    "Edu":        regexp.MustCompile(`<td><span class="label">学历：</span>(?:<span field="">)*([^<]+)(?:</span>)*</td>`),
    
    "Job":        regexp.MustCompile(`<td><span class="label">职业：.*</span>(?:<span field="">)*([^<]+)(?:</span>)*</td>`),
    
    "JobAddress": regexp.MustCompile(`<td><span class="label">工作地：</span>(?:<span field="">)*([^<]+)(?:</span>)*</td>`),
    
    "HasChild":   regexp.MustCompile(`<td><span class="label">.*孩子：</span>(?:<span field="">)*([^<]+)(?:</span>)*</td>`),
    
    "Income":     regexp.MustCompile(`<td><span class="label">月收入：</span>(?:<span field="">)*([^<]+)(?:</span>)*</td>`),
    
    "Jiguan":     regexp.MustCompile(`<td><span class="label">籍贯：</span>(?:<span field="">)*([^<]+)(?:</span>)*</td>`),
    
    "Weight":     regexp.MustCompile(`<td><span class="label">体重：</span>(?:<span field="">)*([^<]+)(?:</span>)*</td>`),
}

func (UserParser UserParser) Analysis(contents []byte) parser.ParseResult {
    
    profile := model.User{}
    
    value := reflect.ValueOf(&profile).Elem()
    
    for key, reg := range regexs {
        str := extractString(contents, reg)
        if str != "" {
            attr := value.FieldByName(key)
            if attr.IsValid() {
                attr.Set(reflect.ValueOf(str))
            }
        } else  {
            log.Warn("未能解析的属性：%str", key)
            continue
        }
    }

    fmt.Println(value)
    
    result := parser.ParseResult{
    
    }
    
    result.ReponseSlice = append(result.ReponseSlice,value)
    
    return result
}

// 正则表达式提取字符串
func extractString(content []byte, reg *regexp.Regexp) string {
    
    match := reg.FindSubmatch(content)
    
    if match == nil || len(match) < 2 {
        return ""
    }
    
    return string(match[1])
}
